package mianshi.singleton;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/**
 * @author: Tangxz
 * @email: 1171702529@qq.com
 * @cate: 2020/11/16 16:41
 */
//阻挡反射
public class LazyMan4 {
    private static boolean flag = false;

    private LazyMan4() {
        synchronized (LazyMan4.class) {
            if (flag == false) {
                flag = true;
            } else {
                throw new RuntimeException("不要试图用反射破坏单例模式");
            }
        }
    }

    private volatile static LazyMan4 LazyMan4;

    public static LazyMan4 getInstance() {
        if (LazyMan4 == null) {
            synchronized (LazyMan.class) {
                if (LazyMan4 == null) {
                    LazyMan4 = new LazyMan4();
                }
            }
        }
        return LazyMan4;
    }
}

class Demo04 {
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {
        LazyMan4 instance = LazyMan4.getInstance();
        //反射
        Constructor<LazyMan4> declaredConstructor = LazyMan4.class.getDeclaredConstructor(null);
        declaredConstructor.setAccessible(true);


        Field flag = LazyMan4.class.getDeclaredField("flag");
        flag.setAccessible(true);
        flag.set(instance,false);//改为false

        LazyMan4 instance2 = declaredConstructor.newInstance();

        System.out.println(instance == instance2);

    }
}